<template>
  <el-card class="blog-create-card">
    <div slot="header">
      <h2>发布博客</h2>
    </div>
    <el-form ref="blogForm" :model="blogForm" :rules="rules" label-width="80px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="blogForm.title"
          placeholder="请输入博客标题"
          size="large"
        ></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input
          type="textarea"
          v-model="blogForm.content"
          placeholder="请输入博客内容"
          :rows="15"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">发布</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
  export default {
    data() {
      return {
        blogForm: {
          title: "",
          content: "",
        },
        rules: {
          title: [
            { required: true, message: "请输入博客标题", trigger: "blur" },
            {
              min: 3,
              max: 100,
              message: "标题长度在 3 到 100 个字符",
              trigger: "blur",
            },
          ],
          content: [
            { required: true, message: "请输入博客内容", trigger: "blur" },
            { min: 10, message: "内容不能少于 10 个字符", trigger: "blur" },
          ],
        },
      };
    },
    methods: {
      async handleSubmit() {
        this.$refs.blogForm.validate(async (valid) => {
          if (valid) {
            try {
              await this.$axios.post("/blog", this.blogForm);
              this.$message.success({
                message: "发布成功",
                type: "success",
                duration: 1000,
              });
              this.$router.push("/blogs");
            } catch (error) {
              this.$message.error("发布失败");
              console.error(error);
              return false;
            }
          } else {
            return false;
          }
        });
      },
      handleCancel() {
        this.$router.go(-1);
      },
    },
  };
</script>

<style scoped>
  .blog-create-card {
    max-width: 1000px;
    margin: 20px auto;
  }
</style>
